import openblt
import time

print('LibOpenBLT version:', openblt.version_get_string())

openblt.firmware_init(openblt.BLT_FIRMWARE_PARSER_SRECORD)

#init module
# Create a session settings object for XCP v10.
session_type= openblt.BLT_SESSION_XCP_V10
session_setting = openblt.BltSessionSettingsXcpV10()
session_setting.timeoutT1 = 1000# Command response timeout in milliseconds.
session_setting.timeoutT3 = 2000 # Start programming timeout in milliseconds.
session_setting.timeoutT4 = 1000 # Erase memory timeout in milliseonds.
session_setting.timeoutT5 = 1000 # Program memory and reset timeout in milliseconds.
session_setting.timeoutT6 = 50 # Command response timeout in milliseconds.
session_setting.timeoutT7 = 2000 # Busy wait timer timeout in milliseconds.
session_setting.seedKeyFile = ""
session_setting.connectMode = 0

transport_type             = openblt.BLT_TRANSPORT_XCP_V10_MBRTU
transport_setting          = openblt.BltTransportSettingsXcpV10MbRtu()
transport_setting.baudrate = 115200
transport_setting.portName = "COM3"
transport_setting.stopBits = 1
transport_setting.parity   = 0
transport_setting.dataBits = 8
transport_setting.destinationAddr = 2

openblt.session_init(session_type=session_type, 
                     session_settings=session_setting, 
                     transport_type=transport_type, 
                     transport_settings=transport_setting)

#connect to bootloader on the target
print("connecting to bootloader, Reset the target if this take a long time")

start_time = time.time()
#循环直到连接成功
while openblt.session_start() != openblt.BLT_RESULT_OK:
    if time.time() - start_time > 10:
        print("Failed to connect to bootloader")
        break
    pass

# #Testing
# print("Connect to the bootloader")

# time.sleep(2)

#读取固件
openblt.firmware_load_from_file("CHLP-GNRC-STM32G071K.s19")

#擦除段segant, 根据要编程的程序
segment_count = openblt.firmware_get_segment_count()

for segment_idx in range(0, segment_count):
    segment_data, segment_addr, segment_len = openblt.firmware_get_segment(segment_idx)
    print("擦除", segment_len, " bytes from addr", hex(segment_addr))

    openblt.session_clear_memory(segment_addr, segment_len)
    
#写入段segant, 根据要编程的程序
for segment_idx in range(0, segment_count):
    segment_data, segment_addr, segment_len = openblt.firmware_get_segment(segment_idx)    
    print("写入", segment_len, " bytes to addr", hex(segment_addr))

    openblt.session_write_data(segment_addr,segment_len, segment_data)





#disconnect
print("finish up to programing session")
openblt.session_stop()

#断开连接
#Terminal modules
openblt.session_terminate()

openblt.firmware_terminate()






